package com.dapeng.cleardatabackend.interceptor.aop;


import com.dapeng.cleardatabackend.annotation.AuthCheck;
import com.dapeng.cleardatabackend.common.ErrorCode;
import com.dapeng.cleardatabackend.common.LoginUserHolder;
import com.dapeng.cleardatabackend.exception.BusinessException;
import com.dapeng.cleardatabackend.model.entity.User;
import com.dapeng.cleardatabackend.model.enums.UserRoleEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 权限校验 AOP
 * @author dapeng
 */
@Aspect
@Component
public class AuthInterceptor {

    /**
     * 拦截器
     *
     * @param joinPoint 连接点
     * @param authCheck 身份验证检查
     * @return {@link Object }
     * @throws Throwable 异常
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        UserRoleEnum mustRoleEnum = authCheck.mustRole();
        // 当前登录用户
        User loginUser = LoginUserHolder.getLoginUser();
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 必须有该权限才通过getUserRole
        UserRoleEnum userRoleEnum = loginUser.getUserRole();
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 如果被封号，直接拒绝
        if (UserRoleEnum.BAN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 必须有管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
            // 用户没有管理员权限，拒绝
            if (!UserRoleEnum.ADMIN.equals(userRoleEnum) && !UserRoleEnum.SUPER_ADMIN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 必须有超管权限
        if (UserRoleEnum.SUPER_ADMIN.equals(mustRoleEnum)) {
            // 用户没有超管权限，拒绝
            if (!UserRoleEnum.SUPER_ADMIN.equals(userRoleEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

